<template>
  <el-config-provider :locale="appStore.locale" :size="(appStore.size as any)">
    <div class="p-5">
      <!-- 查询条件 -->
      <div class="query-condition flex justify-between">
        <div class="condition">
          <el-input class="w-50 mr-3" v-model="searchInfo.menuName" placeholder="菜单名称"></el-input>
          <el-button type="primary" plain @click="reloadSyncTable">
            <i-ep-Refresh />
          </el-button>
          <el-button type="primary" @click="loadSyncMenu">
            <i-ep-Search />
          </el-button>
        </div>
        <div class="button">
          <el-button type="primary" @click="openSyncMenu">菜单同步</el-button>
        </div>
      </div>

      <!-- 表格展示 -->
      <div class="table-content mt-5">
        <el-table row-key="rightId" :data="tableData" border :cell-style="cellStyle" style="width: 100%">
          <el-table-column align="center" type="index" width="55" label="序号"></el-table-column>
          <el-table-column align="center" prop="menuName" label="菜单名称"></el-table-column>
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="menuFunc"
            label="功能配置"
            width="234"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="toMenu"
            label="流转模块"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="toType"
            label="流转条件"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="dataSort"
            label="数据排序"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="dataAuth"
            label="数据权限"
          ></el-table-column>
          <el-table-column align="center" prop="prop" label="操作" width="356" fixed="right">
            <template #default="{ row }">
              <el-button @click="setTableFunction(row, 1)" type="danger" size="small" plain>
                数据权限
              </el-button>
              <el-button @click="setTableFunction(row, 2)" type="warning" size="small" plain>
                功能配置
              </el-button>
              <el-button @click="setTableFunction(row, 3)" type="primary" size="small" plain>
                查询条件
              </el-button>
              <el-button @click="setTableFunction(row, 4)" type="success" size="small" plain>
                流转配置
              </el-button>
              <!-- <el-button @click="updatePage(row)" type="success" size="small">更新页面</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="mt-4">
        <el-pagination
          v-model:current-page="searchInfo.page"
          v-model:page-size="searchInfo.limit"
          background
          layout="prev, pager, next, jumper, total"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 数据权限 -->
    <el-dialog title="数据权限" width="500" v-model="showDialog" :close-on-click-modal="false">
      <div class="p-5">
        <el-form label-width="80px" label-position="left">
          <el-form-item label="数据排序">
            <el-select
              v-model="permissionForm.fieldId"
              v-loading="loadingField"
              placeholder="请选择数据"
              class="w-full"
            >
              <el-option
                v-for="item in fieldSelect"
                :key="item.id"
                :label="item.fieldName"
                :value="item.fieldId"
              ></el-option>
            </el-select>
            <el-radio-group v-model="permissionForm.sortNum" class="mt-5">
              <el-radio label="正序">正序</el-radio>
              <el-radio label="倒序">倒序</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="数据权限">
            <el-select v-model="permissionForm.dataAuth" placeholder="请选择数据权限" class="w-full">
              <el-option
                v-for="item in dataPermission"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button
          :loading="loadingBtn"
          :disabled="!permissionForm.fieldId"
          type="primary"
          @click="savePermission"
        >
          保 存
        </el-button>
      </div>
    </el-dialog>

    <!-- 功能配置 -->
    <el-dialog title="功能配置" width="500" v-model="showDialogFunc" :close-on-click-modal="false">
      <div class="table-content">
        <el-table border :data="tableDataFunc" style="width: 100%">
          <el-table-column align="center" prop="name" label="操作类型"></el-table-column>
          <el-table-column align="center" prop="show" label="是否展示该功能">
            <template #default="{ row }">
              <el-checkbox v-model="row.show"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template #default="{ row }">
              <el-button
                v-if="row.value !== 'add' && row.value !== 'submit' && row.value !== 'check'"
                type="primary"
                size="small"
                @click="setFuncDetail(row)"
              >
                配置
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="flex justify-center mt-5">
        <el-button @click="showDialogFunc = false">取 消</el-button>
        <el-button :loading="loadingBtn" type="primary" @click="saveFunction">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 功能详情配置 -->
    <el-dialog
      title="功能详情配置"
      :width="currentTableFunc && currentTableFunc.value === 'examine' ? 800 : 600"
      v-model="showDialogFuncDetail"
      :close-on-click-modal="false"
    >
      <div class="p-5">
        <el-form label-width="80px" label-position="left">
          <!-- 编辑 -->
          <div v-if="currentTableFunc.value === 'edit'">
            <el-form-item label="编辑规则">
              <el-radio-group v-model="currentTableFunc.config.isEdit">
                <el-radio label="所有字段可编辑"></el-radio>
                <el-radio label="指定字段可编辑"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="选择字段"
              v-if="
                currentTableFunc.config.isEdit && currentTableFunc.config.isEdit === '指定字段可编辑'
              "
            >
              <el-select
                v-model="currentTableFunc.config.fieldId"
                placeholder="请选择字段"
                class="w-full"
                multiple
              >
                <el-option
                  v-for="item in fieldSelect"
                  :key="item.id"
                  :label="item.fieldName"
                  :value="item.fieldId"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>

          <!-- 删除 -->
          <div v-else-if="currentTableFunc.value === 'delete'">
            <el-form-item label="删除规则">
              <el-radio-group v-model="currentTableFunc.config.isDel">
                <el-radio label="可随意删除"></el-radio>
                <el-radio label="按条件删除"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="删除条件"
              v-if="currentTableFunc.config.isDel && currentTableFunc.config.isDel === '按条件删除'"
            >
              <el-select
                v-model="currentTableFunc.config.delCondition"
                multiple
                placeholder="请选择删除条件"
                class="w-full"
              >
                <el-option
                  v-for="item in ['未经流转可删除', '审核未通过可删除']"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>

          <!-- 导出 -->
          <div v-else-if="currentTableFunc.value === 'export'">
            <el-form-item label="导出规则">
              <el-radio-group v-model="currentTableFunc.config.exportType">
                <el-radio label="按表头显示字段导出"></el-radio>
                <el-radio label="导出所有字段为表头"></el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- 导入 -->
          <div v-else-if="currentTableFunc.value === 'import'">
            <el-form-item label="导入模板" class="w-full">
              <el-upload
                accept=".xls,.xlsx"
                :http-request="uploadTemp"
                class="upload-demo w-full"
                drag
                :limit="1"
                v-model:file-list="fileList"
                action="#"
              >
                <i-ep-Upload-filled class="el-icon--upload" />
                <div class="el-upload__text">
                  拖拽文件到此处或者
                  <em>点击上传</em>
                </div>
              </el-upload>
            </el-form-item>
          </div>

          <!-- 审核 -->
          <div v-else-if="currentTableFunc.value === 'examine'">
            <el-form-item label="条件配置" class="w-full">
              <el-button @click="addNewExamConfig" type="primary">
                <i-ep-CirclePlusFilled class="mr-1" />
                新增条件
              </el-button>
            </el-form-item>

            <el-form-item
              class="w-full"
              v-for="(item, index) in currentTableFunc.config.conditionList"
              :key="index"
            >
              <div class="p-5 bg-gray1 rounded-1 shadow">
                <div class="mb-5">
                  <el-button @click="addExamField(item)" type="primary" plain>
                    <i-ep-Plus class="mr-1" />
                    新增字段
                  </el-button>
                  <el-button @click="setExamProcess(item)" type="primary" plain>
                    <i-ep-Tools class="mr-1" />
                    配置流程
                  </el-button>
                  <el-button
                    @click="currentTableFunc.config.conditionList.splice(index, 1)"
                    type="danger"
                    plain
                  >
                    <i-ep-Delete class="mr-1" />
                    删除本条
                  </el-button>
                </div>
                <div class="flex mb-3" v-for="(item__, index__) in item.fieldList">
                  <el-select v-model="item__.fieldId" placeholder="请选择审核字段" class="w-full mr-3">
                    <el-option
                      v-for="k in fieldSelect"
                      :key="k.id"
                      :label="k.fieldName"
                      :value="k.fieldId"
                    ></el-option>
                  </el-select>
                  <el-select
                    @change="item__.value = ''"
                    v-model="item__.condition"
                    placeholder="请选择条件"
                    class="w-full mr-3"
                  >
                    <el-option
                      v-for="k in examConditionSelect"
                      :key="k"
                      :label="k"
                      :value="k"
                    ></el-option>
                  </el-select>
                  <el-input
                    :disabled="item__.condition.indexOf('空') > -1"
                    class="mr-3"
                    placeholder="值"
                    v-model="item__.value"
                  ></el-input>
                  <el-button
                    :disabled="item.fieldList.length === 1"
                    type="danger"
                    link
                    plain
                    @click="item.fieldList.splice(index__, 1)"
                  >
                    <i-ep-Delete />
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end mt-5">
        <el-button @click="showDialogFuncDetail = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 审核流程配置 -->
    <el-dialog
      title="审核流程配置"
      width="1000"
      v-model="showDialogExamine"
      :close-on-click-modal="false"
    >
      <div>
        <div class="flex items-center">
          <el-checkbox v-model="currentExamCondition.notExam">无需审核</el-checkbox>
          <el-tag class="ml-5" type="warning">注：如果该情况无需审核请勾选该项</el-tag>
        </div>

        <!-- 流程图 -->
        <div class="pt-5 flex flex-wrap" v-if="!currentExamCondition.notExam">
          <el-card
            class="w-40 h-25 flex-center relative overflow-inherit! mr-8 last:mr-0 mb-5"
            v-for="(item, index) in currentExamCondition.examPerson"
            :key="item.id"
            @mouseenter.native="item.showDel = true"
            @mouseleave.native="item.showDel = false"
          >
            <el-select v-model="item.userId" placeholder="审核人" class="w-full">
              <el-option
                v-for="item in userSelect"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              ></el-option>
            </el-select>

            <!-- 删除 -->
            <div
              v-if="item.showDel && currentExamCondition.examPerson.length > 1"
              class="absolute top--3 right--3 z-10 cursor-pointer"
              @click="currentExamCondition.examPerson.splice(index, 1)"
            >
              <i-ep-CircleCloseFilled class="hover:color-red4" color="red5" size="5" />
            </div>

            <!-- 新增 -->
            <div
              class="absolute top-38% right--3 z-10 cursor-pointer"
              v-if="index === currentExamCondition.examPerson.length - 1"
              @click="addProcess"
            >
              <i-ep-CirclePlusFilled class="hover:color-blue4" color="blue5" size="5" />
            </div>

            <!-- 线 -->
            <div
              class="absolute top-38% right--7.5 z-10"
              v-if="index !== currentExamCondition.examPerson.length - 1"
            >
              <div class="flex items-center">
                <div class="bg-blue5 block w-3 h-3px"></div>
                <div class="ml--8px mt-3px">
                  <i-ep-CaretRight color="blue5" />
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      <div slot="footer" class="flex justify-end mt-5">
        <el-button @click="showDialogExamine = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 查询条件 -->
    <el-dialog title="查询条件" width="500" v-model="showDialogQuery" :close-on-click-modal="false">
      <div class="flex flex-col">
        <!-- 不同的条件列表 -->
        <div class="mb-3 flex" v-for="(item, index) in queryForm" :key="index">
          <el-select
            @change="changeQueryField(item)"
            v-model="item.fieldId"
            class="w-100%"
            placeholder="选择查询字段"
          >
            <el-option
              v-for="item__ in fieldSelect"
              :key="item__.fieldId"
              :label="item__.fieldName"
              :value="item__.fieldId"
              :disabled="item__.disabled"
            ></el-option>
          </el-select>
          <el-input v-model="item.fieldType" disabled class="mx-3" placeholder="字段类型"></el-input>
          <el-button
            @click="queryForm.splice(index, 1), resetQuerySelectDisabled()"
            type="danger"
            :disabled="queryForm.length === 1"
          >
            <i-ep-Delete />
          </el-button>
        </div>
        <div>
          <el-button type="primary" @click="addQueryCondition">
            <i-ep-CirclePlusFilled class="mr-1" />
            新增一条
          </el-button>
        </div>
      </div>
      <div slot="footer" class="flex justify-center mt-5">
        <el-button @click="showDialogQuery = false">取 消</el-button>
        <el-button :loading="loadingBtn" type="primary" @click="saveQueryCondition">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 流转类型 -->
    <el-dialog title="流转类型" width="800" v-model="showDialogTransfer" :close-on-click-modal="false">
      <div class="flex flex-col">
        <el-form label-width="100px" label-position="left">
          <el-form-item label="流转类型">
            <el-radio-group @change="resetTransferData" v-model="transferForm.toType">
              <el-radio label="不流转"></el-radio>
              <el-radio label="保存后流转"></el-radio>
              <el-radio label="按操作流转"></el-radio>
              <el-radio label="按字段参数流转"></el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 保存后流转 -->
          <div
            class="saved"
            v-if="transferForm.toType === '保存后流转' || transferForm.toType === '按操作流转'"
          >
            <el-form-item label="流转接收人">
              <el-radio-group v-model="transferForm.receiveUser">
                <el-radio label="指定接收人"></el-radio>
                <el-radio label="不指定接收人"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="接收人" v-if="transferForm.receiveUser === '指定接收人'">
              <div class="flex w-full">
                <el-select
                  class="w-80 mr-2"
                  v-model="transferForm.receiveUserOrganId"
                  placeholder="部门"
                  @change="handleOrgChange"
                >
                  <el-option
                    v-for="item in orgSelect"
                    :key="item.orgId"
                    :label="item.orgName"
                    :value="item.orgId"
                  ></el-option>
                </el-select>
                <el-select
                  v-loading="loadSelect"
                  class="w-full"
                  multiple
                  v-model="transferForm.reciverId"
                  placeholder="接收人"
                >
                  <el-option
                    v-for="item in userSelectByOrg"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId"
                  ></el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="选择操作" v-if="transferForm.toType === '按操作流转'">
              <el-select class="w-full" v-model="transferForm.selectHandle" placeholder="请选择操作">
                <el-option label="提交再流转" value="提交再流转"></el-option>
                <el-option label="审核通过再流转" value="审核通过再流转"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="流转模块">
              <el-select
                class="w-full"
                placeholder="请选择接流转到的模块"
                v-model="transferForm.toMenuId"
              >
                <el-option
                  v-for="item in tableDataAll"
                  :key="item.id"
                  :label="item.menuName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 按照字段参数流转 -->
          <el-form-item label="流转条件" v-if="transferForm.toType === '按字段参数流转'">
            <div class="by-field flex flex-col">
              <div class="mb-3">
                <el-button @click="addTransCondition" type="primary">
                  <i-ep-CirclePlusFilled class="mr-1" />
                  新增条件
                </el-button>
              </div>
              <div
                class="mb-3 p-5 shadow bg-gray1"
                v-for="(item, index) in transferForm.fieldConditon"
                :key="index"
              >
                <div class="flex mb-5">
                  <el-select v-model="item.menuId" class="w-100%" placeholder="选择流转模块">
                    <el-option
                      v-for="item__ in tableDataAll"
                      :key="item__.id"
                      :label="item__.menuName"
                      :value="item__.id"
                    ></el-option>
                  </el-select>
                  <el-select
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    v-model="item.reciverId"
                    class="w-100% mx-3"
                    placeholder="选择接收人"
                  >
                    <el-option
                      v-for="item in userSelect"
                      :key="item.userId"
                      :label="item.userName"
                      :value="item.userId"
                    ></el-option>
                  </el-select>
                  <el-button type="primary" @click="addTransferField(item)" plain>
                    <i-ep-Plus class="mr-1" />
                    新增字段
                  </el-button>
                  <el-button
                    @click="transferForm.fieldConditon.splice(index, 1)"
                    class="mr-3"
                    type="danger"
                    plain
                  >
                    <i-ep-Delete class="mr-1" />
                    删除本条
                  </el-button>
                </div>

                <div class="flex mb-3" v-for="(item__, index__) in item.fieldList">
                  <el-select class="mr-3" v-model="item__.fieldId" placeholder="选择字段">
                    <el-option
                      v-for="key in fieldSelect"
                      :key="key.fieldId"
                      :label="key.fieldName"
                      :value="key.fieldId"
                    ></el-option>
                  </el-select>
                  <el-select v-model="item__.condition" placeholder="选择条件">
                    <el-option
                      v-for="k in examConditionSelect"
                      :key="k"
                      :label="k"
                      :value="k"
                    ></el-option>
                  </el-select>
                  <el-input
                    :disabled="item__.condition.indexOf('空') > -1"
                    v-model="item__.value"
                    class="mx-3 w-200px"
                    @blur="judgeIsNumber(item__)"
                    placeholder="值"
                  ></el-input>
                  <el-button
                    :disabled="item.fieldList.length === 1"
                    type="danger"
                    link
                    @click="item.fieldList.splice(index__, 1)"
                  >
                    <i-ep-Delete />
                  </el-button>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-center mt-5">
        <el-button @click="showDialogTransfer = false">取 消</el-button>
        <el-button :loading="loadingBtn" type="primary" @click="saveTransfer">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 同步菜单 -->
    <el-dialog title="菜单同步" :close-on-click-modal="false" v-model="showDialogSync" width="1000">
      <div class="table-content">
        <el-table
          v-loading="loadingMenu"
          @selection-change="handleSelectionChange"
          row-key="rightId"
          border
          :data="menuTreeSelect"
          style="width: 100%"
        >
          <el-table-column align="center" :selectable="selectable" type="selection" width="55" />
          <el-table-column align="center" prop="rightName" label="菜单名称" width="245">
            <template #default="{ row }">
              <span class="w-180px inline-block">{{ row.rightName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="rightUrl" label="菜单链接"></el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="mt-5 flex justify-end">
        <el-button @click="showDialogSync = false">取 消</el-button>
        <el-button :loading="loadingBtn" type="primary" @click="sureSyncMenu">确 定</el-button>
      </div>
    </el-dialog>
  </el-config-provider>
</template>

<script setup lang="ts">
//@ts-nocheck

import { useQueryTable } from '@/utils/hooks/useQueryTable';
import { useAppStore } from '@/store/modules/app';
import XyTools from '@/utils/functions/xy-tools';
import tableDataFuncData from '@/pages/menuConfig/tableDataFuncData';
import {
  loadMenuApi,
  ledgerMenuFormApi,
  ledgerMenuTabApi,
  ledgerMenuTableFieldListApi,
  ledgerMenuAuthFormApi,
  ledgerMenuFuncFormListApi,
  ledgerMenuAuthTabApi,
  ledgerMenuFuncTabApi,
  ledgerMenuQueryFormListApi,
  ledgerMenuQueryTabApi,
  ledgerMenuTosetFormApi,
  ledgerMenuTosetTabApi,
  ledgerMenuDelApi,
  uploadApi,
  userListApi,
  addRightApi,
  delRightApi,
  getUserListByOrgIDApi
} from '@/utils/api/menuConfig';
import config from '@/utils/config';
import axios from 'axios';

const appStore = useAppStore();

const showDialog = ref(false);
const showDialogFunc = ref(false);
const showDialogQuery = ref(false);
const showDialogTransfer = ref(false);
const showDialogFuncDetail = ref(false);
const showDialogExamine = ref(false);
const showDialogSync = ref(false);
const loadingMenu = ref(false);
const loadingField = ref(false);
const loadSelect = ref(false);
const $xy = new XyTools();
const menuTreeSelect = ref([]);
const fieldSelect = ref([]);
const syncList = ref([]);
const userSelect = ref([]);
const orgSelect = ref([]);
const userSelectByOrg = ref([]);
const dataPermission = [
  '可见全部数据',
  '可见本组织与下级组织创建的数据',
  '可见本组织创建的数据',
  '仅可见自己创建的数据'
];
const examConditionSelect = ['值大于', '值小于', '值等于', '值为空', '值不为空'];

const permissionForm = reactive({
  dataAuth: '可见全部数据',
  fieldEname: '',
  fieldId: '',
  fieldName: '',
  menuId: '',
  sortNum: '正序'
}); // 数据权限表单
const queryForm = ref([]); // 查询权限表单
const tableDataAll = ref([]); // 查询权限表单
const transferForm = ref<any>(null); // 流转条件表单
const currentTableFunc = ref(null);
const tableDataFunc = ref([]);
const fileList = ref([]);

let choosedFunction = []; // 已经选择的菜单功能
let currentTable = null;
let currentExamCondition = ref(null); // 选中的审核条件
let menuTree = [];

// 初始化
const init = () => {
  loadMenu();
  loadSyncMenu();
  getUserList();
  loadSyncMenuAll();
};

// 获取用户列表
const getUserList = async () => {
  const res = await userListApi();

  if (res.status === 200) {
    userSelect.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 读取对应的字段信息
const loadFieldList = async (id: string) => {
  loadingField.value = true;
  const res = await ledgerMenuTableFieldListApi({ id });
  loadingField.value = false;

  if (res.status === 200) {
    fieldSelect.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 切换组织
const handleOrgChange = async (val) => {
  loadSelect.value = true;

  const res = await userListApi({
    orgId: val
  });

  loadSelect.value = false;

  if (res.status === 200) {
    userSelectByOrg.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 读取菜单
const loadMenu = async () => {
  loadingMenu.value = true;
  const res = await loadMenuApi({ page: 1, limit: 9999 });
  loadingMenu.value = false;

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      menuTree = res.data;
      menuTreeSelect.value = listToTree(
        res.data.filter((item) => {
          return (
            item.rightIsMeua === '1' &&
            item.rightName !== '系统管理' &&
            item.rightName !== '基础配置管理'
          );
        })
      );
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询已经同步的菜单
const loadSyncMenu = async () => {
  loading.value = true;
  const res = await ledgerMenuTabApi(searchInfo);
  loading.value = false;

  if (res.status === 200) {
    tableData.value = res.data;
    total.value = res.count ? Number(res.count) : 0;
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询已经同步的菜单
const loadSyncMenuAll = async () => {
  loading.value = true;
  const res = await ledgerMenuTabApi({ page: 1, limit: 9999 });
  loading.value = false;

  if (res.status === 200) {
    tableDataAll.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 重置表格
const reloadSyncTable = () => {
  searchInfo.page = 1;
  searchInfo.menuName = '';
  loadSyncMenu();
};

const {
  tableData,
  searchInfo,
  total,
  loading,
  loadingBtn,
  handleSizeChange,
  handleCurrentChange,
  cellStyle
} = useQueryTable(loadSyncMenu);

// 设置不同的菜单功能
const setTableFunction = async (row, type: number) => {
  currentTable = row;
  loadingBtn.value = false;

  if (type === 1) {
    /* 数据权限 */
    showDialog.value = true;
    permissionForm.fieldId = '';
    permissionForm.fieldEname = '';
    permissionForm.fieldName = '';
    loadFieldList(row.id); // 加载菜单已选字段

    if (row.dataAuth) getDataPermissionData(row);
  } else if (type === 2) {
    /* 功能配置 */
    choosedFunction = [];
    showDialogFunc.value = true;
    tableDataFunc.value = JSON.parse(JSON.stringify(tableDataFuncData));
    loadFieldList(row.id); // 加载菜单已选字段
    if (row.menuFunc) getFunctionData(row);
  } else if (type === 3) {
    queryForm.value = [];
    /* 查询条件 */
    queryForm.value.push({
      fieldId: '',
      fieldName: ''
    });

    showDialogQuery.value = true;

    await loadFieldList(row.id); // 加载菜单已选字段

    fieldSelect.value.push(
      {
        fieldId: '审核状态',
        fieldName: '审核状态',
        fieldType: '审核状态',
        fieldEname: 'EXMINE_STATUS'
      },
      {
        fieldId: '流转状态',
        fieldName: '流转状态',
        fieldType: '流转状态',
        fieldEname: 'TRANSFER_STATUS'
      }
    );

    getQueryData(row);
  } else if (type === 4) {
    queryOrgInfo();

    transferForm.value = {
      menuId: row.id,
      toType: '不流转',
      receiveUserOrganId: '',
      receiveUserOrganName: '',
      toMenuName: '',
      toMenuId: '',
      selectHandle: '',
      receiveUser: '',
      receiveUserJson: '',
      reciverId: [],
      fieldId: '',
      fieldName: '',
      fieldEname: '',
      fieldType: '',
      fieldValue: '',
      fieldConditon: []
    };
    /* 流转配置 */
    showDialogTransfer.value = true;

    loadFieldList(row.id); // 加载菜单已选字段

    if (row.toMenu) getTransferData(row);
  }
};

// 获取流转配置
const getTransferData = async (row) => {
  const res = await ledgerMenuTosetTabApi({ menuId: row.id });

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      transferForm.value = res.data[0];

      transferForm.value.reciverId = [];
      transferForm.value.fieldConditon = [];

      if (transferForm.value.receiveUserOrganId) {
        await handleOrgChange(transferForm.value.receiveUserOrganId);
      }

      if (transferForm.value.receiveUserJson) {
        transferForm.value.reciverId = JSON.parse(transferForm.value.receiveUserJson);
      }

      if (transferForm.value.fieldValue) {
        transferForm.value.fieldConditon = JSON.parse(transferForm.value.fieldValue);
      }
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 重置流转条件
const resetTransferData = () => {
  transferForm.value.toMenuName = '';
  transferForm.value.toMenuId = '';
  transferForm.value.selectHandle = '';
  transferForm.value.receiveUser =
    transferForm.value.toType === '保存后流转' || transferForm.value.toType === '按操作流转'
      ? '指定接收人'
      : '';
  transferForm.value.receiveUserJson = '';
  transferForm.value.reciverId = [];
  transferForm.value.fieldId = '';
  transferForm.value.fieldName = '';
  transferForm.value.fieldEname = '';
  transferForm.value.fieldType = '';
  transferForm.value.fieldValue = '';
  transferForm.value.fieldConditon = [];
};

// 获取查询条件
const getQueryData = async (row) => {
  const res = await ledgerMenuQueryTabApi({ menuId: row.id });

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      queryForm.value = res.data;

      nextTick(() => {
        resetQuerySelectDisabled();
      });
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询组织信息
const queryOrgInfo = async () => {
  const res = await axios.get(config.baseUrl + '/cdledger/ledger-menu-do/organList', {
    headers: { token: config.token }
  });

  if (res.data && res.data.status && res.data.status === 200) {
    orgSelect.value = res.data.data;
  } else {
    ElMessage.error(res.data.status.message);
  }
};

// 判断是否为数字
const judgeIsNumber = (row) => {
  if (row.condition && (row.condition === '值大于' || row.condition === '值小于')) {
    const __ISNaN = isNaN(row.value);

    if (__ISNaN) {
      row.value = '';
      ElMessage.warning('当前条件仅支持数字值');
    }
  }
};

// 新增查询条件
const addQueryCondition = () => {
  if (!fieldSelect.value) {
    return ElMessage.error('字段列表为空');
  } else if (queryForm.value.length === fieldSelect.value.length) {
    return ElMessage.error('已达到字段数量总数，无法新增');
  }

  queryForm.value.push({
    fieldId: '',
    fieldName: '',
    fieldType: ''
  });

  resetQuerySelectDisabled();
};

// 改变查询字段
const changeQueryField = (row) => {
  const __field = fieldSelect.value.find((item) => item.fieldId === row.fieldId);

  if (__field) {
    row.fieldType = __field.fieldType;
    row.fieldName = __field.fieldName;
    row.fieldEname = __field.fieldEname;
    row.menuId = currentTable.id;
  }

  resetQuerySelectDisabled();
};

// 重新计算查询条件字段下拉的禁用
const resetQuerySelectDisabled = () => {
  fieldSelect.value.forEach((item) => {
    item.disabled = false;

    let match = queryForm.value.find((item__) => item__.fieldId === item.fieldId);

    if (match) {
      item.disabled = true;
    }
  });
};

// 查询数据权限已有数据
const getDataPermissionData = async (row) => {
  const res = await ledgerMenuAuthTabApi({ menuId: row.id });

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      permissionForm.fieldId = res.data[0].fieldId;
      permissionForm.fieldEname = res.data[0].fieldEname;
      permissionForm.fieldName = res.data[0].fieldName;
      permissionForm.sortNum = res.data[0].sortNum;
      permissionForm.dataAuth = res.data[0].dataAuth;
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询数据权限已有数据
const getFunctionData = async (row) => {
  const res = await ledgerMenuFuncTabApi({ menuId: row.id });

  if (res.status === 200) {
    if (res.data) {
      choosedFunction = res.data;

      tableDataFunc.value.forEach((item) => {
        const match = res.data.find((item_) => item_.funcName === item.name);

        if (match) {
          item.id = match.id;
          item.config = match.ruleContent ? JSON.parse(match.ruleContent) : {};
          item.name = match.funcName;
          item.show = match.funcShow ? Boolean(match.funcShow) : false;
          item.value = match.funcName ? getFunctionValueType(match.funcName) : '';
        }
      });
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 获取类型对应值
const getFunctionValueType = (name: string) => {
  switch (name) {
    case '新增':
      return 'add';
    case '编辑':
      return 'edit';
    case '删除':
      return 'delete';
    case '提交':
      return 'submit';
    case '导入':
      return 'import';
    case '导出':
      return 'export';
    case '审核':
      return 'examine';
    case '查看单条':
      return 'check';
  }
};

// 详细功能配置
const setFuncDetail = (row) => {
  currentTableFunc.value = row;
  showDialogFuncDetail.value = true;
  row.show = true;

  if (row.name === '导入' && row.config) {
    if (row.config.importModelUrl) {
      fileList.value = [
        {
          name: row.config.importModelUrl.split('_')[1]
        }
      ];
    } else {
      fileList.value = [];
    }
  }
};

// 上传模板
const uploadTemp = async (obj) => {
  const __formData = new FormData();

  __formData.append('file', obj.file);

  const res = await uploadApi(__formData);

  if (res.status === 200) {
    currentTableFunc.value.config.importModelUrl = res.fileName;
    obj.onSuccess();
  } else {
    obj.onError();
    ElMessage.error(res.msg);
  }
};

// 新增审核配置
const addNewExamConfig = () => {
  currentTableFunc.value.config.conditionList.push({
    fieldList: [
      {
        fieldId: '',
        condition: '',
        value: ''
      }
    ],
    notExam: false,
    examPerson: [
      {
        id: $xy.RI(),
        name: '',
        userId: '',
        showDel: false
      }
    ]
  });
};

// 设置审核流程
const setExamProcess = (row) => {
  currentExamCondition.value = row;
  showDialogExamine.value = true;
};

// 新增审核字段
const addExamField = (row) => {
  row.fieldList.push({
    fieldId: '',
    condition: '',
    value: '',
    notExam: false,
    examPerson: [
      {
        id: $xy.RI(),
        name: '',
        userId: '',
        showDel: false
      }
    ]
  });
};

// 添加流转条件
const addTransCondition = () => {
  transferForm.value.fieldConditon.push({
    fieldList: [
      {
        fieldId: '',
        condition: '',
        value: ''
      }
    ],
    menuId: '',
    reciverId: []
  });
};

// 添加流转字段
const addTransferField = (row) => {
  row.fieldList.push({
    fieldId: '',
    condition: '',
    value: ''
  });
};

const selectable = (row) => (tableDataAll.value.find((item) => item.id === row.rightId) ? false : true);

// 更新页面
const updatePage = (row) => {};

// 新增进程
const addProcess = () => {
  currentExamCondition.value.examPerson.push({
    id: $xy.RI(),
    name: '',
    userId: '',
    showDel: false
  });
};

// 打开同步菜单弹窗
const openSyncMenu = () => {
  showDialogSync.value = true;
  loadingBtn.value = false;
  syncList.value = [];
};

// 列表转换为 🌲
const listToTree = (data) => {
  const map = {};
  const roots = [];

  data.forEach((item) => {
    map[item.rightId] = { ...item, children: [] };
  });

  // 构建树结构
  data.forEach((item) => {
    const node = map[item.rightId];

    if (item.rightParentId === '0') {
      roots.push(node);
    } else {
      const parent = map[item.rightParentId];

      if (parent) {
        parent.children.push(node);
      }
    }
  });

  return roots;
};

// 同步菜单
const sureSyncMenu = async () => {
  loadingBtn.value = true;

  let removeItem = [];

  for (let i = 0; i < tableDataAll.value.length; i++) {
    const obj = menuTree.find((item__) => item__.rightId === tableDataAll.value[i].id);

    if (!obj) {
      // 需要删除的项
      await ledgerMenuDelApi({ id: tableDataAll.value[i].id });
    }
  }

  if (syncList.value.length === 0) {
    loadingBtn.value = false;
    showDialogSync.value = false;
    reloadSyncTable();
    loadSyncMenuAll();
    ElMessage.success('已同步');
    return;
  }

  let __form = [];

  syncList.value.forEach((item) => {
    __form.push({
      dataAuth: '',
      dataSort: '',
      menuFunc: '',
      menuName: item.rightName,
      menuUrl: item.rightUrl,
      toMenu: '',
      toType: '',
      id: item.rightId
    });
  });

  const res = await ledgerMenuFormApi(__form);

  loadingBtn.value = false;

  if (res.status === 200) {
    ElMessage.success('已同步');
    showDialogSync.value = false;
    reloadSyncTable();
    loadSyncMenuAll();
  } else {
    ElMessage.error(res.msg);
  }
};

// 表格选项修改
const handleSelectionChange = (rows) => {
  syncList.value = rows;
};

// 保存数据权限
const savePermission = async () => {
  const __field = fieldSelect.value.find((item) => item.fieldId === permissionForm.fieldId);
  permissionForm.menuId = currentTable.id;
  permissionForm.fieldEname = __field.fieldEname;
  permissionForm.fieldName = __field.fieldName;
  loadingBtn.value = true;

  const res = await ledgerMenuAuthFormApi(permissionForm);

  loadingBtn.value = false;

  if (res.status === 200) {
    ElMessage.success('操作成功');
    showDialog.value = false;
    loadSyncMenu();
  } else {
    ElMessage.error(res.msg);
  }
};

// 保存功能配置
const saveFunction = async () => {
  let __showTables = JSON.parse(JSON.stringify(tableDataFunc.value)).filter((item) => item.show);

  loadingBtn.value = true;

  const __tree = JSON.parse(JSON.stringify(menuTree));

  __showTables.forEach((item, index) => {
    if (item.value === 'edit') {
      item.ruleSet = item.config.isEdit;
    } else if (item.value === 'delete') {
      item.ruleSet = item.config.isDel;
    } else if (item.value === 'export') {
      item.ruleSet = item.config.exportType;
    } else if (item.value === 'import') {
      item.ruleSet = item.config.importModelUrl;
    } else if (item.value === 'examine') {
      item.ruleSet = item.config.fieldId;
    }

    item.ruleContent = JSON.stringify(item.config);
    item.funcShow = item.show;
    item.funcName = item.name;
    item.menuId = currentTable.id;

    const addItem = choosedFunction.find((item__) => item__.id === item.id);

    if (!addItem) {
      // 新增业务模块的按钮权限
      addRightApi({
        rightName: item.name,
        rightOrder: index + 1,
        rightParentId: currentTable.id,
        rightIsMeua: 2
      });
    }
  });

  choosedFunction.forEach(async (item) => {
    const delItem = __showTables.find((item__) => item__.id === item.id);

    if (!delItem) {
      const menuInfo = __tree.find(
        (k) => k.rightParentId === currentTable.id && k.rightName === item.funcName
      );

      if (menuInfo) {
        // 删除按钮权限
        await delRightApi({
          id: menuInfo.rightId
        });
      } else {
        $xy.log('没有找到菜单信息');
      }
    }
  });

  const res = await ledgerMenuFuncFormListApi(__showTables);

  loadingBtn.value = false;

  if (res.status === 200) {
    ElMessage.success('操作成功');
    showDialogFunc.value = false;
    loadSyncMenu();
    loadMenu();
  } else {
    ElMessage.error(res.msg);
  }
};

// 保存查询条件
const saveQueryCondition = async () => {
  const nullObj = queryForm.value.find((item) => !item.fieldId);

  if (nullObj) return ElMessage.error('部分字段未选择');

  loadingBtn.value = true;

  const res = await ledgerMenuQueryFormListApi(queryForm.value);

  if (res.status === 200) {
    ElMessage.success('操作成功');
    showDialogQuery.value = false;
    loadSyncMenu();
  } else {
    ElMessage.error(res.msg);
  }
};

// 保存流转配置
const saveTransfer = async () => {
  if (transferForm.value.toType === '保存后流转') {
    if (transferForm.value.receiveUser === '指定接收人' && transferForm.value.reciverId.length === 0) {
      return ElMessage.error('未选择接收人');
    } else if (!transferForm.value.toMenuId) {
      return ElMessage.error('未选择流转模块');
    } else {
      transferForm.value.receiveUserJson = JSON.stringify(transferForm.value.reciverId);
      transferForm.value.receiveUserOrganName = orgSelect.value.find(
        (item) => item.orgId === transferForm.value.receiveUserOrganId
      )?.orgName;
      transferForm.value.toMenuName = tableData.value.find(
        (item) => item.id === transferForm.value.toMenuId
      ).menuName;
    }
  } else if (transferForm.value.toType === '按操作流转') {
    if (transferForm.value.receiveUser === '指定接收人' && transferForm.value.reciverId.length === 0) {
      return ElMessage.error('未选择接收人');
    } else if (!transferForm.value.toMenuId) {
      return ElMessage.error('未选择流转模块');
    } else if (!transferForm.value.selectHandle) {
      return ElMessage.error('未选择操作类型');
    } else {
      transferForm.value.receiveUserJson = JSON.stringify(transferForm.value.reciverId);
      transferForm.value.toMenuName = tableData.value.find(
        (item) => item.id === transferForm.value.toMenuId
      ).menuName;
      transferForm.value.receiveUserOrganName = orgSelect.value.find(
        (item) => item.orgId === transferForm.value.receiveUserOrganId
      )?.orgName;
    }
  } else if (transferForm.value.toType === '按字段参数流转') {
    if (transferForm.value.fieldConditon.length === 0) {
      return ElMessage.error('请至少新增一条条件配置');
    } else {
      const nullObj = transferForm.value.fieldConditon.find((item) => {
        let flag = false;

        if (!item.menuId || item.reciverId.length === 0 || item.fieldList.length === 0) {
          flag = true;
        } else {
          const __nullObj = item.fieldList.find((item__) => {
            if (item__.condition.indexOf('空') > -1) {
              return !item__.fieldId || !item__.condition;
            } else {
              return !item__.fieldId || !item__.condition || item__.value === '';
            }
          });

          if (__nullObj) {
            flag = true;
          }
        }

        return flag;
      });

      if (nullObj) {
        return ElMessage.error('条件配置不能有空值');
      } else {
        let menuNameArr = [];

        const __arr = transferForm.value.fieldConditon.map((item) => item.menuId);

        if (__arr && __arr.length > 0) {
          __arr.forEach((item) => {
            const __obj = tableDataAll.value.find((item__) => item__.id === item);

            if (__obj) {
              menuNameArr.push(__obj.menuName);
            }
          });
        }

        /* 格式化表单数据 */
        const __field = fieldSelect.value.find(
          (item) => item.fieldId === transferForm.value.fieldConditon[0].fieldList[0].fieldId
        );

        transferForm.value.fieldName = __field.fieldName;
        transferForm.value.fieldEname = __field.fieldEname;
        transferForm.value.fieldType = __field.fieldType;
        transferForm.value.fieldValue = JSON.stringify(transferForm.value.fieldConditon);
        transferForm.value.toMenuName = menuNameArr.join(',');
      }
    }
  }

  loadingBtn.value = true;

  const res = await ledgerMenuTosetFormApi(transferForm.value);

  loadingBtn.value = false;

  if (res.status === 200) {
    ElMessage.success('操作成功');
    showDialogTransfer.value = false;
    loadSyncMenu();
  } else {
    ElMessage.error(res.msg);
  }
};

searchInfo.menuName = '';
init();
</script>

<style lang="scss" scoped>
:deep(.el-form--inline .el-form-item:nth-child(even)) {
  margin-right: 0;
}

:deep(.el-checkbox__input.is-disabled .el-checkbox__inner) {
  background-color: #eee;
}
</style>
